package com.example.demo.config;

import com.example.demo.common.BizCodeEnum;
import com.example.demo.common.Res;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.*;

/**
 * @author kaka
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    //处理自定义异常
    @ExceptionHandler(value = Exception.class)
    public Res<Void> exceptionHandler(Exception e) {
        log.error("系统错误堆栈信息", e);
        return Res.failed(BizCodeEnum.SYSTEM_ERROR);
    }

    //处理空指针异常
    @ExceptionHandler(value = NullPointerException.class)
    public Res<Void> nullPointerExceptionHandler(NullPointerException e) {
        log.error("系统发生空指针异常", e);
        return Res.failed(BizCodeEnum.NULL_POINTER_ERROR);
    }

    /**
     * 处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常，详情继续往下看代码
     *
     * @Validated @Valid仅对于表单提交有效，对于以json格式提交将会失效）
     */

    @ExceptionHandler(BindException.class)
    public Res<Void> bindExceptionHandler(BindException e) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        List<String> msgList = new ArrayList<>();
        for (ObjectError allError : allErrors) {
            DefaultMessageSourceResolvable argument = (DefaultMessageSourceResolvable) Objects.requireNonNull(allError.getArguments())[0];
            msgList.add(String.format("%s:%s", Objects.requireNonNull(argument.getCodes())[0], allError.getDefaultMessage()));
        }
        log.error("bindExceptionHandler异常:{}", msgList);
        return Res.failed(msgList.toString());
    }

    /**
     * @param e 异常类
     * @return 响应
     * @Validated @Valid 前端提交的方式为json格式有效
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Res<Void> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        List<String> msgList = new ArrayList<>();
        for (ObjectError allError : allErrors) {
            DefaultMessageSourceResolvable argument = (DefaultMessageSourceResolvable) Objects.requireNonNull(allError.getArguments())[0];
            msgList.add(String.format("%s:%s", Objects.requireNonNull(argument.getCodes())[0], allError.getDefaultMessage()));
        }
        log.error("methodArgumentNotValidExceptionHandler异常:{}", msgList);
        return Res.failed(msgList.toString());
    }


    /**
     * 处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是javax.validation.ConstraintViolationException
     *
     * @param ex
     * @return
     * @NotBlank @NotNull @NotEmpty
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public Res<Void> constraintViolationExceptionHandler(ConstraintViolationException ex) {

        Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
        Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
        List<String> msgList = new ArrayList<>();
        while (iterator.hasNext()) {
            ConstraintViolation<?> cvl = iterator.next();
            msgList.add(cvl.getMessageTemplate());
        }
        return Res.failed(msgList.toString());
    }


}
